package cn.zyjblogs.starter.mybatisplus.config;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;

/**
 * Set<Integer> ==>  string
 *
 * @Date 2022-10-08
 */
public class SetToStringHandler extends BaseTypeHandler<Set> {


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Set list, JdbcType jdbcType) throws SQLException {
        if (!CollectionUtils.isEmpty(list)) {
            preparedStatement.setString(i, String.join(",", list));
        } else {
            preparedStatement.setString(i, null);
        }

    }

    @Override
    public Set getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        return result == null ? null : Set.of(StringUtils.commaDelimitedListToStringArray(result));
    }

    @Override
    public Set getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        return result == null ? null : Set.of(StringUtils.commaDelimitedListToStringArray(result));
    }

    @Override
    public Set getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        return result == null ? null : Set.of(StringUtils.commaDelimitedListToStringArray(result));
    }
}